package marmalius.craft.firemaking;

import java.util.ArrayList;
import java.util.List;

import marmalius.Player;
import marmalius.PlayerHandler;
import marmalius.client;
import marmalius.item.ItemService;
import marmalius.map.MapService;
import marmalius.player.Animation;
import marmalius.player.GoalPoint;
import marmalius.player.GoalType;
import marmalius.player.SkillType;


public class FireMaking {
	private static final FireMaking instance = new FireMaking();
	
	public static final int FIREOBJID = 2732;
	private List<Fire> fires;
	
	public FireMaking() {
		fires = new ArrayList<Fire>();
	}
	
	public void process(int time) {
		List<Fire> needToDelete = new ArrayList<Fire>();
		for (Fire fire : fires) {
			if (fire.getBurnTime() > 0) {
				if (fire.getBurnTime() - time > 0)
					fire.setBurnTime(fire.getBurnTime() - time);
				else {
					fire.setBurnTime(0);
					MapService.getInstance().removeObject(fire);
					PlayerHandler.getInstance().removeObjectAll(fire.getCoordX(), fire.getCoordY(), fire.getHeightLevel(), 10);
					needToDelete.add(fire);
				}
			}
		}
		for (Fire fire : needToDelete)
			fires.remove(fire);
	}
	
	public void startFireMaking(Player player, int itemID) {
		FireInfo fire = new FireInfo(player, itemID);
		if (fire.getItemID() != 0) {
			if (fire.getReqLevel() > player.getSkillLevel(SkillType.FIREMAKING)) {
				player.sendPlayerMessage("You need " + fire.getReqLevel() + "+ firemaking to burn "+ ItemService.getInstance().getItemTemplate(itemID).getName() + " logs.");
				return ;
			}
			player.startAnimation(Animation.FIREMAKING);
			player.sendPlayerMessage("You attempt to light the logs...");
			player.setGoalPoint(new GoalPoint(0, player.getAbsX(), player.getAbsY(), GoalType.FIREMAKING, fire));
			player.ForceCanDoGoal();
		}
	}
	
	public void createFireMaking(Player player, FireInfo fireInfo) {
		player.startAnimation(Animation.STOPANIMATION); //TODO player must move
		if (player.getInventory().hasItem(fireInfo.getItemID())) {
			player.getInventory().removeItem(fireInfo.getItemID(), 1);
			Fire fire = new Fire(player.absX, player.absY, (byte)player.heightLevel, fireInfo.getBurnTime());
			fires.add(fire);
			PlayerHandler.getInstance().replaceObjectAll(2732, fire.getCoordX(), fire.getCoordY(), fire.getHeightLevel(), 0, 10);
			MapService.getInstance().addObject(fire);
			player.sendPlayerMessage("...the fire catches and the logs begin to burn!");
			((client)player).addSkillXP(fireInfo.getExperience(), SkillType.FIREMAKING.getValue());
		}
	}
	
	public static FireMaking getInstance() { return instance; }
}
